

var express = require('express')
var router = express.Router()
var { user_model, homehot_model } = require('../db/model')
var { FindOneDataMore, InsertManyData, UpdateTableData, FindTableData, RemoveTableData } = require('../db')
var axios = require("axios")
const { getToken, checkToken } = require('../utils/token')
var multer = require("multer")

router.get("/test", (req, res) => {
    res.json({
        code: 200,
        msg: "Test = TEst = 测试Api 接口 ",
        result: null
    })
})

// Vue3.0 接口的接口 

router.post("/register", (req, res) => {
    var body = req.body;
    // 先判断再去注册
    FindOneDataMore({
        model: user_model,
        query: {
            $or: [
                {
                    phone: body.phone
                }
            ]
        },
        res,
        callback(result) {
            if (result) {
                res.json({
                    code: 401,
                    msg: "用户已经存在,请重新注册",
                    result,
                })
            } else {
                body.time = new Date()
                InsertManyData({
                    model: user_model,
                    data: body,
                    msg: "注册成功",
                    res
                })
            }
        }
    })

})

// router.post("/students", (req, res) => { //写入学生信息
//     var body = req.body
//     console.log(body);
//     InsertManyData({
//         model: students_model,
//         data: body,
//         msg: "写入成功",
//         res,
//     })
// })


// router.post("/students", (req, res) => { //写入留言板
//     var body = req.body
//     console.log(body);
//     InsertManyData({
//         model: students_model,
//         data: body,
//         msg: "写入成功",
//         res,
//     })
// })



// 登录
router.post("/login", (req, res) => {
    var body = req.body;
    FindOneDataMore({
        model: user_model,
        query: body,
        res,
        callback(result) {
            if (result) {
                // Token  
                var token = getToken(body)  // 用户名和密码得到一个 token 
                res.json({
                    code: 200,
                    msg: "登录成功",
                    result,
                    token
                })
            } else {
                res.json({
                    code: 401,
                    msg: "登录失败,用户名或者密码错误",
                    result,
                })
            }
        }
    })
})

// 发送验证码 
router.post("/sendcaptcha", (req, res) => {
    var body = req.body;
    // 先去查询一下 
    // 再去发送验证码 
    FindOneDataMore({
        model: user_model,
        query: body,
        res,
        callback(result) {
            if (result) {
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/sent", {
                    params: body // {phone:xxxxxx}
                })
                    .then(({ data }) => {
                        console.log(data)
                        if (data.code == 200) {
                            res.json({
                                code: 200,
                                data,
                                msg: '验证码发送成功'
                            })
                        } else {
                            res.json({
                                code: 401,
                                data,
                                msg: '验证码发送失败'
                            })
                        }

                    })
            } else {
                res.json({
                    code: 401,
                    msg: '手机号未注册,请先注册',
                    result
                })
            }
        }
    })
})

// 校验验证码 
router.post("/chechcaptcha", (req, res) => {
    var body = req.body;  // phone captcha
    FindOneDataMore({
        model: user_model,
        query: { phone: body.phone },
        res,
        callback(result) {
            if (result) {
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/verify", {
                    params: body // {phone:xxxxxx}
                })
                    .then(({ data }) => {
                        // console.log(data);
                        // data.code==200
                        if (true) {
                            res.json({
                                code: 200,
                                data,
                                msg: '验证码校验成功'
                            })
                        } else {
                            res.json({
                                code: 401,
                                data,
                                msg: '验证码校验失败'
                            })
                        }
                    })
            } else {
                res.json({
                    code: 401,
                    msg: '手机号未注册,请先注册',
                    result
                })
            }
        }
    })
})

// 获取个人信息 
router.post("/getusreinfo", (req, res) => {
    checkToken(req, res, ({ username }) => {
        FindOneDataMore({
            model: user_model,
            query: { username },
            msg: '获取个人信息成功',
            res
        })
    })
})

//获取首页热榜
router.get("/gethot", (req, res) => {
        
    FindTableData({
            model: homehot_model,
            msg: '获取首页热榜成功',
            res
    })

})

// 上传文件 
const storage = multer.diskStorage({  // 硬盘存储 
    destination: function (req, file, cb) {
        cb(null, './public/images/uploads')
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = "WH2114__" + Date.now() + '-' + Math.round(Math.random() * 1E9)   // 文件名、
        cb(null, file.fieldname + '-' + uniqueSuffix + file.originalname)
    }
})

const upload = multer({ storage: storage }).any()

// 上传文件 
router.post("/uploadfile", upload, (req, res) => {
    var path = req.files[0].path
    res.json({
        code: 200,
        msg: "上传成功",
        path,
        result: path
    })
})

// 修改用户信息 
router.post("/changeuser", (req, res) => {
    var body = req.body;
    checkToken(req, res, ({ username }) => {
        UpdateTableData({
            model: user_model,
            query: { username },
            data: {
                $set: body
            },
            res,
            msg: "成功"
        })
    })
})


// // 权限列表 
// router.post("/rolelist", (req, res) => {
//     checkToken(req, res, ({ username }) => {
//         FindTableData({
//             model: role_model,
//             res,
//             msg: "获取权限列表成功"
//         })
//     })
// })

// // role 添加
// router.post("/roleadd", (req, res) => {
//     checkToken(req, res, ({ username }) => {
//         InsertManyData({
//             model: role_model,
//             data: req.body,
//             res,
//             msg: '添加角色成功'
//         })
//     })
// })


// // role 修改
// router.post('/roleupdate', (req, res) => {
//     checkToken(req, res, ({ username }) => {
//         UpdateTableData({
//             model: role_model,
//             query: {
//                 _id: req.body._id
//             },
//             data: req.body, //
//             res,
//             msg: '修改成功'
//         })
//     })
// })

// 添加用户
router.post("/useradd", (req, res) => {
    var body = req.body;
    // 先判断再去注册
    FindOneDataMore({
        model: user_model,
        query: {
            $or: [
                {
                    username: body.username
                },
                {
                    phone: body.phone
                }
            ]
        },
        res,
        callback(result) {
            if (result) {
                res.json({
                    code: 401,
                    msg: "用户已经存在,请重新添加",
                    result,
                })
            } else {
                body.time = new Date()
                InsertManyData({
                    model: user_model,
                    data: body,
                    msg: "添加成功",
                    res
                })
            }
        }
    })
})

router.post("/homehot", (req, res) => {  //添加商品列表
    var body = req.body;
    FindOneDataMore({
        model: homehot_model,
        query: {
            $or: [
                {
                    gsColorCode: body.gsColorCode
                }
            ]
        },
        res,
        callback(result) {
            if (result) {
                res.json({
                    code: 401,
                    msg: "该商品已经添加，跳过添加",
                    result,
                })
            } else {
                body.time = new Date()
                InsertManyData({
                    model: homehot_model,
                    data: body,
                    msg: "添加成功",
                    res
                })
            }
        }
    })
})

// // role 修改
// router.post('/userlist', (req, res) => {
//     console.log(req.body)
//     var query = {}
//     var { keyword, role } = req.body;
//     if (keyword && role) {
//         query = {
//             username: new RegExp(keyword),
//             role: role * 1
//         }
//     } else if (role) {
//         query = {
//             role: role * 1
//         }
//     } else if (keyword) {
//         query = {
//             username: new RegExp(keyword)
//         }
//     }
//     checkToken(req, res, ({ username }) => {
//         FindTableData({
//             model: user_model,
//             query: query,
//             res,
//             msg: '查询成功'
//         })
//     })
// })

// 删除用户 
router.post('/userremove', (req, res) => {
    checkToken(req, res, ({ username }) => {
        RemoveTableData({
            model: user_model,
            query: req.body,
            res,
            msg: '删除成功'
        })
    })
})

// 修改用户 
router.post('/userupdate', (req, res) => {
    checkToken(req, res, ({ username }) => {
        UpdateTableData({
            model: user_model,
            query: {
                _id: req.body._id
            },
            data: req.body,
            res,
            msg: '修改成功'
        })
    })
})

module.exports = router;